/**
 * 红冲操作的按钮
 *    新建红冲
 *    红冲记录
 */
import React, { Component } from "react";
import moment from "moment";
import { Divider, Form, Input, InputNumber, Modal, Row, Col, DatePicker, Button, Spin, message } from "antd";
import { messages, queryCurrencyPrecision } from "share/common";
import Condition from "components/condition";
import paymentService from "../../corporate-payment-report.service";

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const { If, Else } = Condition;

@Form.create()
class OperateReverseInvoice extends Component {
  state = {
    loading: false,
    recordLoading: false,
    newReverseVisible: false,
    reverseRecordVisible: false,
    reverseList: [],
  };

  // 新建红冲
  handleReverse = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.paymentScheduleId = this.props.info.id;
        // 当地时间，非UTC时间
        values.reverseBookDate = values.reverseBookDate.format("YYYY-MM-DD HH:mm:ss");
        this.setState({ loading: true });
        paymentService
          .reverseInvoice(values)
          .then(() => {
            this.setState({ newReverseVisible: false });
            message.success(messages("finance-9.key108") /*保存成功*/);
            this.props.onRefresh();
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }
    });
  };

  // 红冲记录
  getReverseList = () => {
    this.setState({
      recordLoading: true,
      reverseRecordVisible: true,
    });
    paymentService
      .getReverseRecord(this.props.info.id)
      .then((res) => {
        this.setState({ reverseList: res.data || [] });
      })
      .finally(() => {
        this.setState({ recordLoading: false });
      });
  };

  renderOperate = () => {
    const { paymentScheduleType, reverseInvoiceInfo } = this.props.info;
    const newReverse = (
      <p
        onClick={(e) => {
          e.stopPropagation();
          this.setState({ newReverseVisible: true });
        }}
      >
        <a>{messages("finance-9.key109") /*新建红冲*/}</a>
      </p>
    );
    const reverseRecord = (
      <p
        onClick={(e) => {
          e.stopPropagation();
          this.getReverseList();
        }}
      >
        <a>{messages("finance-9.key110") /*红冲记录*/}</a>
      </p>
    );
    let showOperate = [];
    if (paymentScheduleType === 1001 && reverseInvoiceInfo) {
      reverseInvoiceInfo.reverseInvoiceEnabled && showOperate.push(newReverse);
      reverseInvoiceInfo.reverseInvoiceAvailable && showOperate.push(reverseRecord);
    }
    return (
      <Condition>
        <If value={showOperate.length}>
          {showOperate[0]}
          {showOperate[1]}
        </If>
        <Else>-</Else>
      </Condition>
    );
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      currencyCode,
      invoiceViewDTO,
      planedAndAssociateAmount,
      writeOffAmount,
      reversedAmount,
      availableAmount,
    } = this.props.info;
    const { loading, recordLoading, newReverseVisible, reverseRecordVisible, reverseList } = this.state;
    const currencyPrecision = queryCurrencyPrecision(currencyCode);
    return (
      <div style={{ display: "inline-block" }}>
        {this.renderOperate()}

        {/*新建红冲*/}
        {newReverseVisible && (
          <Modal
            title={messages("finance-9.key109") /*新建红冲*/}
            visible={newReverseVisible}
            width={720}
            confirmLoading={loading}
            onOk={this.handleReverse}
            onCancel={() => this.setState({ newReverseVisible: false })}
          >
            <div>
              {messages("finance-9.key100") /*费用总额*/}：{currencyCode}{" "}
              {this.filterMoney(invoiceViewDTO.amount, currencyPrecision)}
            </div>
            <div>
              {messages("finance-9.key111") /*已支付金额*/}：{currencyCode}{" "}
              {this.filterMoney(planedAndAssociateAmount, currencyPrecision)}
              <Divider type="vertical" />
              {messages("finance-9.key112") /*已核销金额*/}：{currencyCode}{" "}
              {this.filterMoney(writeOffAmount, currencyPrecision)}
              <Divider type="vertical" />
              {messages("finance-9.key113") /*已红冲金额*/}：{currencyCode}{" "}
              {this.filterMoney(reversedAmount, currencyPrecision)}
              <Divider type="vertical" />
              {messages("finance-9.key114") /*可红冲金额*/}：{currencyCode}{" "}
              {this.filterMoney(availableAmount, currencyPrecision)}
            </div>
            <Divider />
            <Form className="new-form">
              <FormItem label={messages("finance-9.key115") /*本次红冲金额*/}>
                <Row style={{ width: "66%", marginBottom: 0 }}>
                  <Col span={12}>
                    <Input disabled value={currencyCode} />
                  </Col>
                  <Col span={11} offset={1}>
                    {getFieldDecorator("reverseAmount", {
                      rules: [
                        {
                          required: true,
                          message: messages("common.please.input") /*请输入*/,
                        },
                        {
                          validator: (item, value, callback) => {
                            if (value === 0) {
                              callback(messages("finance-9.key116") /*红冲金额不能为0*/);
                            }
                            callback();
                          },
                        },
                      ],
                    })(
                      <InputNumber
                        min={0}
                        max={availableAmount}
                        precision={currencyPrecision}
                        style={{ width: "100%" }}
                      />
                    )}
                  </Col>
                </Row>
              </FormItem>
              <FormItem label={messages("finance-9.key117") /*红冲记账日期*/}>
                {getFieldDecorator("reverseBookDate", {
                  rules: [
                    {
                      required: true,
                      message: messages("common.select") /*请选择*/,
                    },
                  ],
                  initialValue: moment(new Date()),
                })(<DatePicker placeholder={messages("finance-9.key118") /*请选择日期*/} />)}
              </FormItem>
              <FormItem label={messages("common.remark") /*备注*/}>
                {getFieldDecorator("remark", {
                  rules: [
                    {
                      max: 100,
                      message: messages("common.max.characters.length", {
                        arg1: 100,
                      }) /*最多输入{arg1}个字符*/,
                    },
                  ],
                })(<TextArea placeholder={messages("common.please.input") /*请输入*/} />)}
              </FormItem>
            </Form>
          </Modal>
        )}

        {/*红冲记录*/}
        {reverseRecordVisible && (
          <Modal
            title={messages("finance-9.key110") /*红冲记录*/}
            visible={reverseRecordVisible}
            width={720}
            bodyStyle={{ maxHeight: "70vh", overflow: "auto" }}
            onCancel={() => this.setState({ reverseRecordVisible: false })}
            footer={[
              <Button key="cancel" onClick={() => this.setState({ reverseRecordVisible: false })}>
                {messages("common.cancel") /*取消*/}
              </Button>,
            ]}
          >
            <Spin spinning={recordLoading}>
              {reverseList.map((item, index) => (
                <div key={item.id}>
                  <Row>
                    <Col span={8}>{item.reverseBookDate.slice(0, 10)}</Col>
                    <Col span={8}>
                      {item.currencyCode}{" "}
                      {this.filterMoney(item.reverseAmount, queryCurrencyPrecision(item.currencyCode))}
                    </Col>
                    <Col span={8}>{item.remark}</Col>
                  </Row>
                  <If value={index < reverseList.length - 1}>
                    <Divider />
                  </If>
                </div>
              ))}
            </Spin>
          </Modal>
        )}
      </div>
    );
  }
}

export default OperateReverseInvoice;
